package com.xiaojian.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaojian.blog.constant.WebConstant;
import com.xiaojian.blog.dao.CommentPOMapper;
import com.xiaojian.blog.dao.ContentPOMapper;
import com.xiaojian.blog.exception.TipException;
import com.xiaojian.blog.model.CommentPO;
import com.xiaojian.blog.model.CommentPOExample;
import com.xiaojian.blog.model.ContentPO;
import com.xiaojian.blog.model.VO.CommentVO;
import com.xiaojian.blog.service.CommentService;
import com.xiaojian.blog.service.ContentService;
import com.xiaojian.blog.utils.DateKit;
import com.xiaojian.blog.utils.TaleUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 评论服务的实现类
 */
@Service
public class CommentServiceImpl implements CommentService {

    private static Logger LOGGER = LoggerFactory.getLogger(CommentServiceImpl.class);

    @Resource
    private CommentPOMapper commentPOMapper;

    @Resource
    private ContentService contentService;


    @Override//插入一条评论
    @Transactional
    public String insertComment(CommentPO commentPO) {
        if (null == commentPO) {
            return "评论对象为空";
        }
        if (StringUtils.isBlank(commentPO.getAuthor())) {
            commentPO.setAuthor("热心网友");
        }
        if (StringUtils.isNotBlank(commentPO.getMail()) &&
                !TaleUtils.isEmail(commentPO.getMail())) {
            return "请输入正确的邮箱格式";
        }
        if (StringUtils.isBlank(commentPO.getContent())) {
            return "评论内容不能为空";
        }
        if (commentPO.getContent().length() < 5 || commentPO.getContent().length() > 2000) {
            return "评论字数在5-2000个字符";
        }
        if (null == commentPO.getCid()) {
            return "评论文章不能为空";
        }
        ContentPO contentPO = contentService.getContents(String.valueOf(commentPO.getCid()));
        if (null == contentPO) {
            return "不存在的文章";
        }
        commentPO.setOwnerId(contentPO.getAuthorId());//作者id
        commentPO.setStatus("not_audit");
        commentPO.setCreated(DateKit.getCurrentUnixTime());
        commentPOMapper.insertSelective(commentPO);

        //更新文章的评论信息
        ContentPO content = new ContentPO();
        content.setCid(contentPO.getCid());
        content.setCommentsNum(contentPO.getCommentsNum() + 1);
        contentService.updateContentByCid(content);

        return WebConstant.SUCCESS_RESULT;
    }

    @Override//获取所有的评论
    public PageInfo<CommentVO> getComments(Integer cid, int page, int limit) {
        if (null != cid) {
            PageHelper.startPage(page, limit);
            CommentPOExample commentPOExample = new CommentPOExample();
            commentPOExample.createCriteria().andCidEqualTo(cid)
                    .andParentEqualTo(0)
                    .andStatusIsNotNull().andStatusEqualTo("approved");
            commentPOExample.setOrderByClause("coid desc");

            List<CommentPO> commentPOList
                    = commentPOMapper.selectByExampleWithBLOBs(commentPOExample);
            PageInfo<CommentPO> commentPOPageInfo = new PageInfo<>(commentPOList);//包含评论原型的分页集
            PageInfo<CommentVO> result = copyPageInfo(commentPOPageInfo);
            if (commentPOList.size() != 0) {
                List<CommentVO> commentVOS = new ArrayList<>(commentPOList.size());
                commentPOList.forEach(commentPO -> {
                    CommentVO commentVO = new CommentVO(commentPO);
                    commentVOS.add(commentVO);
                });
                result.setList(commentVOS);
            }
            return result;
        }
        return null;
    }



    @Override
    public PageInfo<CommentPO> getCommentsWithPage(CommentPOExample commentPOExample, int page, int limit) {
        PageHelper.startPage(page, limit);
        List<CommentPO> commentPOList = commentPOMapper.selectByExampleWithBLOBs(commentPOExample);
        PageInfo<CommentPO> result = new PageInfo<>(commentPOList);
        return result;
    }

    @Override//通过id获得评论信息
    public CommentPO getCommentById(Integer coid) {
        if ( null != coid) {
            return commentPOMapper.selectByPrimaryKey(coid);
        }
        return null;
    }

    @Override
    @Transactional
    public void delete(Integer coid, Integer cid) {
        if (null == coid) {
            throw new TipException("评论的主键为空");
        }
        commentPOMapper.deleteByPrimaryKey(coid);
        ContentPO contentPO = contentService.getContents(cid + "");
        if (null == contentPO && contentPO.getCommentsNum() > 0) {
            ContentPO content = new ContentPO();
            content.setCid(cid);
            content.setCommentsNum(contentPO.getCommentsNum() - 1);
            contentService.updateContentByCid(content);
        }
    }

    @Override//更新评论
    @Transactional
    public void update(CommentPO commentPO) {
        if (null != commentPO && null != commentPO.getCoid()) {
            commentPOMapper.updateByPrimaryKeyWithBLOBs(commentPO);
        }
    }


    /**
     * copy原来的分页信息,除了数据
     *
     */
    private <T> PageInfo<T> copyPageInfo(PageInfo ordinal) {
        PageInfo<T> returnVo = new PageInfo<T>();
        returnVo.setPageSize(ordinal.getPageSize());
        returnVo.setPageNum(ordinal.getPageNum());
        returnVo.setEndRow(ordinal.getEndRow());
        returnVo.setTotal(ordinal.getTotal());
        returnVo.setHasNextPage(ordinal.isHasNextPage());
        returnVo.setHasPreviousPage(ordinal.isHasPreviousPage());
        returnVo.setIsFirstPage(ordinal.isIsFirstPage());
        returnVo.setIsLastPage(ordinal.isIsLastPage());
        returnVo.setNavigateFirstPage(ordinal.getNavigateFirstPage());
        returnVo.setNavigateLastPage(ordinal.getNavigateLastPage());
        returnVo.setNavigatepageNums(ordinal.getNavigatepageNums());
        returnVo.setSize(ordinal.getSize());
        returnVo.setPrePage(ordinal.getPrePage());
        returnVo.setNextPage(ordinal.getNextPage());
        return returnVo;
    }
}
